#include <stdio.h>
#include <stdlib.h>

#include "debug.h"
#include "arg_parse.h"
#include "buf.h"
#include "file_bin.h"
#include "file_bit.h"

int close_file( FILE* );

int main( int argc, char **argv )
{
	arg_parse_init( argc, argv );
	char *infile_n=NULL,*outfile_n=NULL,*infmt=NULL,*outfmt=NULL;
	FILE *infile=NULL, *outfile=NULL;

	if ( (infile_n = arg_input_file()) != NULL )
	{
		if ( (infile = fopen(infile_n,"r")) == NULL )
		{
			ERROR("Cannot open input file %s\n", infile_n);
			return -1;
		}
	} 
	
	if ( (outfile_n = arg_output_file()) != NULL )
	{
		if ( (outfile = fopen(outfile_n,"w")) == NULL )
		{
			ERROR("Cannot open output file %s\n", outfile_n);
			return -1;
		}
	}
	
	if ( ( infmt = arg_input_fmt() ) != NULL )
	{
		if ( !arg_valid_ifmt( infmt ) )
		{
			ERROR("Unknown inputfile format\n");
			return -1;
		} 
	} 
	
	if ( ( outfmt = arg_output_fmt() ) != NULL )
	{
		if ( !arg_valid_ofmt( outfmt ) )	
		{
			ERROR("Unknown output file\n");
			return -1;
		}
	}
	
	if ( (infile == NULL) || (outfile == NULL) || 
		(infmt == NULL) || (outfmt == NULL) )
	{
		ERROR("Need more params\n");
	}
	
	buf b; 
	memset(&b, 0, sizeof(buf));
	//buf_init( &b );

	int convert=1;
	int ret;
	//PRINT("\n");

	while ( convert )
	{
		ret = file_bin_load( infile, &b );
		//PRINT("\n");

		if (ret < 1)
		{
			convert = 0;
		} else
		{
			if ( strncmp( outfmt, "bin", 3 ) == 0 )
			{
				file_bin_store( outfile, &b );
			}
			else if ( strncmp( outfmt, "bit", 3 ) == 0 )
			{
				file_bit_store( outfile, &b );
			} else if ( strncmp( outfmt, "c", 1 ) == 0 )
			{
				file_c_store( outfile, &b );
			
			} else if ( strncmp( outfmt, "html", 4) == 0 )
			{
				file_html_store( outfile, &b );
			} else if ( strncmp( outfmt, "hex", 3 ) == 0 )
			{
				file_hex_store( outfile, &b );
			} else
			{
				ERROR("Canno convert\n");
			}
		}
	}

	//buf_destroy( &b );

	fclose( infile );
	fclose( outfile );

	return 0;
}


int close_file( FILE *f )
{
	if ( f != NULL )
		return fclose( f );
	return 0;
}

